package com.haolijun.eecms.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.haolijun.eecms.common.R;
import com.haolijun.eecms.dao.TbApplyDao;
import com.haolijun.eecms.entity.TbApply;
import com.haolijun.eecms.service.ActiveService;
import com.haolijun.eecms.service.ApplyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName ApplyServiceImpl
 * @Description TODO
 * @Author hljstart
 * @Date 2023/3/12 11:45
 * @Version 1.0
 */
@Service
@Slf4j
public class ApplyServiceImpl implements ApplyService {

    @Autowired
    private TbApplyDao applyDao;

    @Autowired
    private ActiveService activeService;

    @Override
    public int deleteApplyByAcid(Integer acId){
        int rows = applyDao.delete(acId);
        return rows;
    }

    @Override
    public R applyActiveOrCancel(TbApply apply) {
        // 1、获取当前报名人的id
        int userId = StpUtil.getLoginIdAsInt();
        apply.setUserId(userId);
        // 2、查看是否已经报名
        // 3、判断是否在报名时间段
        // 3.1、查询活动详情
        HashMap map = activeService.searchActiveInfo(apply.getAcId());
        String startTimeStr = (String) map.get("startTime");
        String endTimeStr = (String) map.get("endTime");
        boolean isApply = (boolean) map.get("isApply");
        // 3.2、获取当前时间
        DateTime now = new DateTime();
        DateTime startTime = DateUtil.parse(startTimeStr);
        DateTime endTime = DateUtil.parse(endTimeStr);
        if(!isApply){
            // 判断时间是否符合
            if (now.isAfterOrEquals(startTime)){
                return R.error().message("活动已经开始无法报名");
            }else if(now.isAfterOrEquals(endTime)){
                return R.error().message("活动已经结束无法报名");
            }
            // 4、报名
            apply.setApplyTime(new Date());
            applyDao.applyActive(apply);
        }else {
            // 判断时间是否符合
            if (now.isAfterOrEquals(startTime)){
                return R.error().message("活动已经开始无法取消报名");
            }else if(now.isAfterOrEquals(endTime)){
                return R.error().message("活动已经结束无法取消报名");
            }
            // 取消报名
            applyDao.cancelActive(apply);
        }
        return R.ok();
    }

    @Override
    public int searchUserIsApply(Map param) {
        return applyDao.searchUserIsApply(param);
    }

}
